# coding=utf-8
#       highscores.py      
#       
#       Copyright 2008 Dirk B. <dirkbo@googlemail.com>
#       
#       This program is free software; you can redistribute it and/or modify
#       it under the terms of the GNU General Public License as published by
#       the Free Software Foundation; either version 2 of the License, or
#       (at your option) any later version.
#       
#       This program is distributed in the hope that it will be useful,
#       but WITHOUT ANY WARRANTY; without even the implied warranty of
#       MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#       GNU General Public License for more details.
#       
#       You should have received a copy of the GNU General Public License
#       along with this program; if not, write to the Free Software
#       Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
#       MA 02110-1301, USA.
import os

class HighScores():
	
	def __init__(self):
		#enthält die lokalen highscores
		self.items = []
		#enthält die online geholten items
		self.oeigener = -1
		self.oerster = -1
		self.oeigener = -1
		self.obesser = -1
		self.oschlechter = -1
		self.mode = 0
		self.level = ''
		#self.maphash = ""
		#self.load()
		
	def set(self,level, mode):
		self.mode = mode
		t = level.rpartition('.lev')
		self.level = t[0]
		
	def load_alt(self):
		filename = os.path.join("data/highscores", self.level+'_'+str(self.mode)+'_'+"scores.dat")
		self.items = []
		if os.path.isfile (filename):
			fp = open(filename)
			content = fp.read()
		
			player = ""
			score = ""
			typ = ""
			readscore = 1
			readplayer = 1
		
			for i in range(0, len(content)):
				if content[i] == '\n':
					if readplayer:
						readplayer = 0
					elif readscore: 
						readscore = 0	
					else:
						self.add(HighScoreEntry(player, score, typ))
						readplayer = 1
						readscore = 1
						player = ""
						score = ""
						typ = ""
				else:
					if readplayer:
						player += content[i]
					elif readscore:
						score += content[i]
					else:
						typ += content[i]
				
			fp.close()
		else:
			fp = open(filename, "w")
			res = ""
			fp.close()
			
	def load(self):
		filename = os.path.join("data/highscores", self.level+'_'+str(self.mode)+'_'+"scores.dat")
		self.items = []
		if os.path.isfile (filename):
			fp = open(filename)
			content = fp.read()
			print "Loading Highscores: ", filename
			##Inhalt Zeile für Zeile in Array laden
			line = []
			line.append("")
			lcount = 0
			for i in range(0, len(content)):
				if content[i] == '\n':
					line.append("")
					#print "Zeile komplett: ", line[lcount]
					lcount += 1	
				else:
					line[lcount] += content[i]

			for i in range(0, len(line)):
				if line[i] == "highscore":
					player = line[i+1]
					score = line[i+2]
					typ = line[i+3]
					geist = line[i+4]
					self.add(HighScoreEntry(player, score, typ, geist))	
				elif line[i] == "online_erster":
					player = line[i+1]
					score = line[i+2]
					typ = line[i+3]
					geist = line[i+4]
					self.oerster = HighScoreEntry(player, score, typ, geist)
				elif line[i] == "online_besser":
					player = line[i+1]
					score = line[i+2]
					typ = line[i+3]
					geist = line[i+4]
					self.obesser = HighScoreEntry(player, score, typ, geist)
				elif line[i] == "online_schlechter":
					player = line[i+1]
					score = line[i+2]
					typ = line[i+3]
					geist = line[i+4]
					self.oschlechter = HighScoreEntry(player, score, typ, geist)
				elif line[i] == "online_eigener":
					player = line[i+1]
					score = line[i+2]
					typ = line[i+3]
					self.oeigener = HighScoreEntry(player, score, typ)

				
	def load_online(self, mapcode, mode, service):
		import urllib
		import online
		print "Frage online Highscores für " + mapcode +" ab."
		parameter = urllib.urlencode({'uc': service.ucode, 'mp': mapcode, 'mode': mode})
		o = urllib.urlopen (service.server + "/billgame/service/getrecords.php", parameter)
		content = o.read()
		print "Seite gefunden: "
		print content
		#Ergebnis verarbeiten
		line = []
		line.append("")
		lcount = 0
		for i in range(0, len(content)):
			if content[i] == '\n':
				line.append("")
				#print "Zeile komplett: ", line[lcount]
				lcount += 1	
			else:
				line[lcount] += content[i]
				
		for i in range(0, len(line)):
			if line[i] == "online_erster":
				player = line[i+1]
				score = line[i+2]
				typ = line[i+3]
				geist = line[i+4]
				self.oerster = HighScoreEntry(player, score, typ, geist)
			elif line[i] == "online_besser":
				player = line[i+1]
				score = line[i+2]
				typ = line[i+3]
				geist = line[i+4]
				self.obesser = HighScoreEntry(player, score, typ, geist)
			elif line[i] == "online_schlechter":
				player = line[i+1]
				score = line[i+2]
				typ = line[i+3]
				geist = line[i+4]
				self.oschlechter = HighScoreEntry(player, score, typ, geist)
			elif line[i] == "online_eigener":
				player = line[i+1]
				score = line[i+2]
				typ = line[i+3]
				self.oeigener = HighScoreEntry(player, score, typ)
		print "-----"
		
		
	def save(self):
		filename = os.path.join("data/highscores", self.level+'_'+str(self.mode)+'_'+"scores.dat")
		fp = open(filename, "w")
		res = ""
		for item in self.items:
			res += "highscore\n" + item.name + "\n" + str(item.score) + "\n" + str(item.gtyp) + "\n" + str(item.replay) + "\n"
		if self.oerster != -1:
			res += "online_erster\n" + self.oerster.name + "\n" + str(self.oerster.score) + "\n" + str(self.oerster.gtyp) + "\n" + str(self.oerster.replay) + "\n"
		if self.obesser != -1:
			res += "online_besser\n" + self.obesser.name + "\n" + str(self.obesser.score) + "\n" + str(self.obesser.gtyp) + "\n"+ str(self.oerster.replay) + "\n"
		if self.oeigener != -1:
			res += "online_eigener\n" + self.oeigener.name + "\n" + str(self.oeigener.score) + "\n" + str(self.oeigener.gtyp) + "\n" +str(self.oerster.replay) + "\n"
		if self.oschlechter != -1:
			res += "online_schlechter\n" + self.oschlechter.name + "\n" + str(self.oschlechter.score) + "\n" + str(self.oschlechter.gtyp) + "\n" +str(self.oerster.replay) + "\n"
		fp.write(res)
		fp.close()
		
	def add(self, item):
		newl = []
		inserted = 0
		count = 10
		if len(self.items) == 0:
			newl.append(item)
			inserted = 1
		else:
			for i in range(0, len(self.items)):
				##Wenn mehr als 5(count) Einträge vorhanden, abbrechen
				if count <= 0:
					return
				if self.mode != 2:
					if int(item.score) <= int(self.items[i].score):
						newl.append(self.items[i])
					else:
						if inserted == 0:
							newl.append(item)
							newl.append(self.items[i])
							inserted = i+1
						else:
							newl.append(self.items[i])
				else:
					#print item.score + "_" + i.score
					if int(item.score) >= int(self.items[i].score):
						newl.append(self.items[i])
					else:
						if inserted == 0:
							newl.append(item)
							newl.append(self.items[i])
							inserted = i+1
						else:
							newl.append(self.items[i])
				count -= 1
		
		# Wenn noch nicht angehängt und weniger als 10 Einträge, Score anhängen	
		if inserted == 0 and count > 0:
			newl.append(item)
			inserted = len(newl)

		self.items = newl
		
		##Nicht mehr benötigte Replays löschen, bzw. in Löschliste aufnehemn
		
		return inserted
		

class HighScoreEntry():
	
	def __init__(self, name, score, gtyp, ghost=-1):
		self.name = name
		self.score = score
		self.gtyp = gtyp
		self.replay = ghost
